package org.example.book.state;

import org.example.book.service.OrderServiceInterface;
import org.example.book.state.pojo.Order;
import org.example.book.util.RedisCommonProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.stereotype.Service;

@Service
public class OrderStateMachineService implements OrderServiceInterface {

    // 注入状态机，与状态机进行交互
    @Autowired
    private StateMachine<OrderState, OrderStateChangeAction> stateMachine;

    @Autowired
    private StateMachinePersister<OrderState, OrderStateChangeAction, String> persister;

    @Autowired
    private RedisCommonProcessor redisCommonProcessor;

    public Order createOrder(String productId) {
        String orderI = "OID" + productId;
        Order order = Order.builder()
                .orderId(orderI)
                .productId(productId)
                .orderState(OrderState.ORDER_WAIT_PAY).build();
        redisCommonProcessor.set(orderI, order);
        Message<OrderStateChangeAction> message = MessageBuilder
                .withPayload(OrderStateChangeAction.ORDER_WAIT_PAY)
                .setHeader("order", order).build();
        // 将message传递给spring状态机
        if (changeStateAction(message, order)) {
            return order;
        }
        return null;
    }

    public Order pay(String orderId) {
        Order order = (Order) redisCommonProcessor.get(orderId);
        Message<OrderStateChangeAction> message = MessageBuilder
                .withPayload(OrderStateChangeAction.PAY_ORDER)
                .setHeader("order", order).build();
        if (changeStateAction(message, order)) {
            return order;
        }
        return null;
    }

    public Order send(String orderId) {
        Order order = (Order) redisCommonProcessor.get(orderId);
        Message<OrderStateChangeAction> message = MessageBuilder.withPayload(OrderStateChangeAction.SEND_ORDER)
                .setHeader("order", order).build();
        if (changeStateAction(message, order)) {
            return order;
        }
        return null;
    }

    public Order receive(String orderId) {
        Order order = (Order) redisCommonProcessor.get(orderId);
        Message<OrderStateChangeAction> message = MessageBuilder.withPayload(OrderStateChangeAction.RECEIVE_ORDER)
                .setHeader("order", order).build();
        if (changeStateAction(message, order)) {
            return order;
        }
        return null;
    }

    @Override
    public String getPayUrl(String orderId, Float price, Integer payType) {
        return "";
    }

    @Override
    public void friendPay(String sourceCustomer, String orderId, String targetCustomer, String payResult, String role) {

    }

    private boolean changeStateAction(Message<OrderStateChangeAction> message, Order order) {
        try {
            stateMachine.start();
            // 从redis缓存中读取状态机，缓存的key为orderId + "STATE"
            persister.restore(stateMachine, order.getOrderId() + "STATE");
            // 将message发送给lister
            boolean res = stateMachine.sendEvent(message);
            // 将更改的订单状态的状态机 存储到redis缓存中
            persister.persist(stateMachine, order.getOrderId() + "STATE");
            return res;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            stateMachine.stop();
        }
    }
}
